import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Box, Typography, TextField, Button, Avatar, Divider, CircularProgress, IconButton } from '@mui/material';
import { Send as SendIcon, ArrowBack as ArrowBackIcon } from '@mui/icons-material';
import { useMessages } from '../MessagesContext';
import { useAuth } from '../../auth/AuthContext';
import { MessageService } from '../services/MessageService';

interface MessageDialogProps {
  messageId?: number;
  newConversation?: {
    userId: number;
    userName: string;
  };
  onMessageSent?: (message: any) => void;
}

// 使用React.memo优化组件渲染性能
const MessageDialog: React.FC<MessageDialogProps> = React.memo(({ messageId, newConversation, onMessageSent }) => {
  console.log('MessageDialog 组件渲染，props:', { messageId, newConversation, onMessageSent });
  
  const [message, setMessage] = useState('');
  const [conversation, setConversation] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [otherUser, setOtherUser] = useState<{id: string, name: string} | null>(null);
  const { messages, sendMessage, markAsRead } = useMessages();
  const { user } = useAuth();
  const messagesEndRef = useRef<HTMLDivElement>(null);
  
  // 使用useCallback优化加载对话的函数
  const loadConversation = useCallback(async () => {
    if (!user) return;
    
    let userId: number | null = null;
    
    // 如果是新对话，使用传入的用户ID
    if (newConversation) {
      userId = newConversation.userId.toString();
      setOtherUser({
        id: newConversation.userId.toString(),
        name: newConversation.userName
      });
    } 
    // 如果是现有对话，从消息中获取对方ID
    else if (messageId) {
      const selectedMessage = messages.find(msg => msg.id === messageId);
      if (selectedMessage) {
        userId = selectedMessage.senderId === user.id 
          ? selectedMessage.receiverId 
          : selectedMessage.senderId;
          
        setOtherUser({
          id: userId,
          name: selectedMessage.senderId === user.id 
            ? selectedMessage.receiverName || '未知用户'
            : selectedMessage.senderName || '未知用户'
        });
      }
    }
    
    if (userId) {
      try {
        setLoading(true);
        console.log('开始加载对话，userId:', userId);
        
        // 获取对话内容
        const conversationData = await MessageService.getConversation(userId);
        console.log('获取到的对话数据:', conversationData);
        console.log('对话数据长度:', conversationData?.length);
        
        setConversation(conversationData);
        
        // 标记消息为已读
        if (messageId) {
          const selectedMessage = messages.find(msg => msg.id === messageId);
          if (selectedMessage && !selectedMessage.isRead && selectedMessage.receiverId === user.id) {
            await markAsRead(messageId);
          }
        }
        
        // 滚动到最新消息
        scrollToBottom();
      } catch (error) {
        console.error('加载对话失败:', error);
      } finally {
        setLoading(false);
      }
    }
  }, [messageId, messages, newConversation, user, markAsRead]);
  
  // 当messageId或newConversation变化时加载对话
  useEffect(() => {
    console.log('MessageDialog useEffect 触发，messageId:', messageId, 'newConversation:', newConversation, 'user:', user);
    loadConversation();
  }, [loadConversation]);
  
  const scrollToBottom = () => {
    setTimeout(() => {
      messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, 100);
  };
  
  const handleSendMessage = async () => {
    if (!message.trim() || !otherUser || !user) return;
    
    try {
      setLoading(true);
      const sentMessage = await sendMessage({
        receiverId: otherUser.id,
        content: message.trim(),
      });
      
      // 清空输入框
      setMessage('');
      
      // 更新对话列表
      setConversation(prev => [...prev, sentMessage]);
      
      // 通知父组件消息已发送
      if (onMessageSent) {
        onMessageSent(sentMessage);
      }
      
      // 滚动到最新消息
      scrollToBottom();
    } catch (error) {
      console.error('发送消息失败:', error);
    } finally {
      setLoading(false);
    }
  };
  
  const formatTime = (timestamp: string) => {
    const date = new Date(timestamp);
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };
  
  const formatDate = (timestamp: string) => {
    const date = new Date(timestamp);
    return date.toLocaleDateString([], { year: 'numeric', month: 'long', day: 'numeric' });
  };
  
  // 渲染加载状态
  if (loading && conversation.length === 0) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
        <CircularProgress />
      </Box>
    );
  }
  
  // 如果没有选中的消息或新对话，显示空状态
  if (!messageId && !newConversation) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
        <Typography variant="body1" color="text.secondary">
          选择一个对话开始聊天
        </Typography>
      </Box>
    );
  }
  
  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* 对话头部 */}
      <Box sx={{ p: 2, borderBottom: 1, borderColor: 'divider', display: 'flex', alignItems: 'center' }}>
        <Avatar sx={{ mr: 2 }}>{otherUser?.name.charAt(0).toUpperCase()}</Avatar>
        <Typography variant="h6">{otherUser?.name}</Typography>
      </Box>
      
      {/* 消息列表 */}
      <Box sx={{ flexGrow: 1, overflow: 'auto', p: 2 }}>
        {console.log('当前conversation状态:', conversation, '长度:', conversation.length)}
        {conversation.length === 0 ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
            <Typography variant="body1" color="text.secondary">
              暂无消息，开始聊天吧
            </Typography>
          </Box>
        ) : (
          conversation.map((msg, index) => {
            const isCurrentUser = msg.senderId === user?.id;
            const showDate = index === 0 || (
              new Date(msg.timestamp).toDateString() !== 
              new Date(conversation[index - 1].timestamp).toDateString()
            );
            
            return (
              <React.Fragment key={msg.id}>
                {showDate && (
                  <Box sx={{ textAlign: 'center', my: 2 }}>
                    <Typography variant="caption" color="text.secondary">
                      {formatDate(msg.timestamp)}
                    </Typography>
                  </Box>
                )}
                <Box
                  sx={{
                    display: 'flex',
                    justifyContent: isCurrentUser ? 'flex-end' : 'flex-start',
                    mb: 2,
                  }}
                >
                  {!isCurrentUser && (
                    <Avatar sx={{ mr: 1, width: 32, height: 32 }}>
                      {otherUser?.name.charAt(0).toUpperCase()}
                    </Avatar>
                  )}
                  <Box
                    sx={{
                      maxWidth: '70%',
                      p: 1.5,
                      borderRadius: 2,
                      bgcolor: isCurrentUser ? 'primary.main' : 'grey.100',
                      color: isCurrentUser ? 'white' : 'text.primary',
                    }}
                  >
                    <Typography variant="body1">{msg.content}</Typography>
                    <Typography
                      variant="caption"
                      sx={{
                        display: 'block',
                        textAlign: 'right',
                        mt: 0.5,
                        color: isCurrentUser ? 'rgba(255, 255, 255, 0.7)' : 'text.secondary',
                      }}
                    >
                      {formatTime(msg.timestamp)}
                    </Typography>
                  </Box>
                  {isCurrentUser && (
                    <Avatar sx={{ ml: 1, width: 32, height: 32 }}>
                      {user?.username?.charAt(0).toUpperCase() || 'U'}
                    </Avatar>
                  )}
                </Box>
              </React.Fragment>
            );
          })
        )}
        <div ref={messagesEndRef} />
      </Box>
      
      {/* 消息输入框 */}
      <Box sx={{ p: 2, borderTop: 1, borderColor: 'divider' }}>
        <Box sx={{ display: 'flex' }}>
          <TextField
            fullWidth
            variant="outlined"
            placeholder="输入消息..."
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && !e.shiftKey && handleSendMessage()}
            disabled={loading}
            size="small"
            sx={{ mr: 1 }}
          />
          <Button
            variant="contained"
            color="primary"
            endIcon={<SendIcon />}
            onClick={handleSendMessage}
            disabled={!message.trim() || loading}
          >
            发送
          </Button>
        </Box>
      </Box>
    </Box>
  );
});

export default MessageDialog;